import ImportData from "@/components/ImportData";
import { s_freezeShipping, s_getSelectData, s_getShippingInfo, s_getTableInfo, s_operateInfo, s_saveShippingInfo, s_updateInfo } from "@/services/basis";
import { getSelection } from "@/services/selections";
import { SwitcherFilled } from "@ant-design/icons";
import { ActionType, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useModel, useRequest } from "@umijs/max";
import { Button, Card, Col, message, Modal, Row, Space, Table, TableColumnProps, Tag, Typography } from "antd";
import moment from "moment";
import { Item } from "rc-menu";
import React, { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [selectedRowKeys,setSelectedRowKeys]=useState<React.Key[]>([]);
    const [open,setOpen]=useState(false);
    const [etype,setEtype]=useState(0);
    const [itemCategory,setItemCategory]=useState([]);

    const table_ref=useRef<ActionType>();
    const form_ref=useRef<ProFormInstance>();

    const { initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    useRequest(async ()=>await getSelection({source:'base_industry',x_id:1}),{
        onSuccess:(data)=>{
           const x=data.map((item:any)=>({value:item.id,label:item.name}));
        //    alert(JSON.stringify(x));
           setItemCategory(x);
        }
    });

    // id,code,name,sname,connector,telephone,
// mobilephone,email,country,province,
// city,adress,level,status,operater_id,
// operate_time,creditcode,source_orgid,regist_time,
//  salecategory,purchasecategory,present,bustype,
// source_orgname,soruce_creditcode,salecategory2,purchasecategory2
interface DataType{
    id:number,
    code:string,name:string,sname:string,connector:string,telephone:string,
    mobilephone:string,email:string,country:string,province:string,
    city:string,address:string,level:number,status:number,operater_id:number,
    operate_time:string,creditcode:string,source_orgid:number,regist_time:string,
    purchasecategory:string,salecategory:string,present:string,bustype:number,
    source_orgname:string,source_creditcode:string,
    salecategory2:string,purchasecategory2:string,
}

const columns:ProColumns<DataType>[]=[
    // {dataIndex:'id',title:'ID'},
    {dataIndex:'code',title:'编码'},{dataIndex:'name',title:'名称'},{dataIndex:'sname',title:'简称'},
    {dataIndex:'connector',title:'联系人'},
    // {dataIndex:'telephone',title:'电话'},{dataIndex:'mobilephone',title:'手机号'},
    // {dataIndex:'email',title:'电子邮箱'},{dataIndex:'country',title:'国家'},{dataIndex:'province',title:'省'},
    // {dataIndex:'city',title:'城市'},
    {dataIndex:'address',title:'详细地址'},
    {dataIndex:'level',title:'等级'},
    {dataIndex:'creditcode',title:'统一社会信用代码'},
    // {dataIndex:'source_orgid',title:'操作组织ID'}, {dataIndex:'salecategory',title:'供货类目',hidden:true},
    {dataIndex:'present',title:'法定代表人'},{dataIndex:'purchasecategory',title:'采购类目',hidden:true},
    {dataIndex:'source_orgname',title:'注册来源组织'},
    // {dataIndex:'source_creditcode',title:'注册来源组织证号'},
    {dataIndex:'operater_id',title:'操作人ID'},
    {dataIndex:'salecategory2',title:'供货类目'},{dataIndex:'purchasecategory2',title:'采购类目'},
    {dataIndex:'operate_time',title:'更新时间',
      render:(text)=>moment(moment(text?.toString()).toDate()).format('YYYY-MM-DD'),
    },
    {dataIndex:'regist_time',title:'注册时间',valueType:'date'},
    {dataIndex:'bustype',
        title:'供销类型',
        fixed:'right',
        width:100,
        render:(text)=>{
            switch(text){
                case 1: return <Tag style={{width:80,textAlign:'center'}}>供应商</Tag>;
                case 2: return <Tag color='gold' style={{width:80,textAlign:'center'}}>店铺</Tag>;
                case 3: return <Tag color="blue" style={{width:80,textAlign:'center'}}>供应商+店铺</Tag>;
            }
        }
    },
    {dataIndex:'status',
     width:60,
     title:'状态',
     fixed:'right',
     render:(text)=>{
        switch(text){
          case 1: return <Tag>正常</Tag>;
          case 2: return <Tag color="blue">关闭</Tag>;
          case 3: return <Tag color="red">删除</Tag>;
        }
     }
    },
];

    async function add(){
        setSelectedRowKeys([]);
        setEtype(1);
        setOpen(true);
        table_ref.current?.reset?.();
    }
    async function edit(){
        if(selectedRowKeys.length==0)
            message.warning('请先选择要编辑的行。');
        else if(selectedRows[0].status==2||selectedRows[0].status==3) 
            message.warning('不能编辑已关闭、已删除的记录。请先恢复再操作');
        else{
            setEtype(0);
            setOpen(true);
        }
    }
    async function save(){
        setOpen(false);
        setSelectedRowKeys([]);
        const fdata2=form_ref.current?.getFieldsValue();
        const fdata={...fdata2,
            operate_time:moment(moment(fdata2.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
            regist_time:fdata2.registime?moment(moment(fdata2.regist_time).toDate()).format('YYYY-MM-DD HH:mm:ss'):null,
            operater_id:initialState?.currentUser?.userid
        }
        //source,x_id,operater_id,etype,fdata  通用的表格保存
        const x=await s_updateInfo({source:'vcdocument',x_id:1,operater_id:initialState?.currentUser?.userid,etype,fdata});
        if(x.success){
            message.success('数据保存成功。');
            setOpen(false);
            setEtype(1);
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('数据保存失败，请检查。');
    }

    async function operate(otype:number){
        const id=selectedRows[0].id;
        //s_operateInfo({source:'base_ware',operater_id:1,type:tabKey,otype,id})通用表格操作冻结删除
        const x=await s_operateInfo({source:'vcdocument',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});

        if(x.success){
            message.success('更新成功。');
            table_ref.current?.reloadAndRest?.();
        }else
           message.error('更新失败，请联系管理员。');
    }
    
//================================================================================================
    return (
        <>
        <ProCard title='店铺供应商总档案管理' style={{height:'85vh',overflow:'auto'}} 
        extra={<Space>
            <Button onClick={()=>add()}>新增</Button>
            <Button onClick={()=>edit()}>编辑</Button>
            
            <Button onClick={()=>operate(2)}>关闭</Button>
            <Button onClick={()=>operate(3)}>删除</Button>
            <Button onClick={()=>operate(1)}>恢复</Button>
            <Space.Compact>
                  <Button>店铺</Button>
                  <ImportData  x_id={1} source='importdata' tdata={{data:'base_custom'}} operater_id={initialState?.currentUser?.userid} />
            </Space.Compact>
            <Space.Compact>
                  <Button>供应商</Button>
                  <ImportData  x_id={1} source='importdata' tdata={{data:'base_vendor'}} operater_id={initialState?.currentUser?.userid} />
            </Space.Compact>
            </Space>}>
            {/* {JSON.stringify(selectedRows)} */}
            {/* {JSON.stringify(selectedRowKeys)} */}
            <ProTable<DataType> 
            actionRef={table_ref}
            search={false} 
            columns={columns}
            rowKey='id'
            options={false}
            rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys,
                onChange:(selectedRowKeys,selectedRows)=>{
                    setSelectedRows(selectedRows);
                    setSelectedRowKeys(selectedRowKeys);
                    setSelectedLineKeys(selectedRowKeys);
                },
            }}
             onRow={(record)=>{
              return {
                  onClick:()=>{
                     const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRowKeys([k]);
                     setSelectedRows([record]);
                     setSelectedLineKeys([k]);
              },
            }
           }}
            request={async (params)=>{
                // alert(JSON.stringify(selectedRowKeys));
                var id=0;
                if(selectedRowKeys.length!=0)
                    id=Number.parseInt(selectedRowKeys[0].toString());
                const x=await s_getTableInfo({source:'v_vcdocument',x_id:1,id:id});  //通用的表格取数函数
                return{
                    data:x.data,
                    success:true,
                }
            }}
            scroll={{
                y:'65vh', 
            }}
            pagination={{
                defaultPageSize:10,
            }}
        
        />
        <Modal title={etype==0?'编辑店铺供应商档案':'新增店铺供应商档案'} destroyOnClose closable onCancel={()=>setOpen(false)}
            open={open} onOk={()=>form_ref.current?.submit()} width={1100} 
        >
             <ProForm submitter={false} formRef={form_ref} 
               onFinish={()=>save()}
               initialValues={etype==1?{
                       operate_time:moment().format('YYYY-MM-DD'),
                        status:1,
                       level:1,bustype:1,
                       operater_id:initialState?.currentUser?.userid
                   }:{
                      ...selectedRows[0],
                       salecategory:selectedRows[0]?.salecategory==null?null:JSON.parse(selectedRows[0]?.salecategory),
                       purchasecategory:selectedRows[0]?.purchasecategory==null?null:JSON.parse(selectedRows[0]?.purchasecategory),
                      operate_time:moment(moment(selectedRows[0]?.operate_time).toDate()).format('YYYY-MM-DD'),
                      regist_time:selectedRows[0]?.regist_time?moment(moment(selectedRows[0]?.regist_time).toDate()).format('YYYY-MM-DD HH:mm:ss'):null,
                 }}
             >
                <Row gutter={8}>
                    <Col span={7}>
                          <ProFormText name='x_id' hidden/>
                          <ProFormText name='id' hidden/>
                          <ProFormText name='code' label='店铺供应商编码' 
                          rules={[{required:true,message:'必输项'}]}/>
                          <ProFormText name='name' label='店铺供应商名称'
                           rules={[{required:true,message:'必输项'}]}/>
                          <ProFormText name='creditcode' label='统一社会信用代码' />
                          <ProFormText name='present' label='法人代表'  />
                          <ProFormText name='sname' label='店铺供应商简称'/>
                          <ProFormText name='connector' label='联系人' />
                          <ProFormText name='telephone' label='手机号' />
                          <ProFormText name='source_orgid' label='推荐来自于' /> 
                    </Col>
                    <Col span={2}></Col>
                    <Col span={7}>
                         <ProFormText name='mobilephone' label='电话' />
                          <ProFormText name='email' label='电子邮箱' />
                          <ProFormText name='country' label='国家' />
                         <ProFormText name='province' label='省/自治区' />
                         <ProFormText name='city' label='城市' />
                         <ProFormText name='address' label='详细地址' />
                         <ProFormDatePicker name='regist_time' label='注册时间' />
                    </Col>
                    <Col span={1}></Col>
                    <Col span={7}>
                         
                         <ProFormRadio.Group name='bustype' label='业务类型' rules={[{required:true,message:'必输项'}]}
                            options={[{value:1,label:'供货商'},{value:2,label:'店铺'},{value:3,label:'供货+店铺'}]}
                         />
                         <ProFormSelect name='salecategory' label='供货类目' showSearch mode="multiple"
                            // onChange={(value)=>{alert(JSON.stringify(value));}}
                            request={async ()=>itemCategory}
                            />
                         <ProFormSelect name='purchasecategory' label='采购类目' showSearch mode="multiple"
                             request={async ()=>itemCategory}
                         />
                         
                         <ProFormText name='level'  label='等级/1-9级' tooltip='按累计交易量划分，以1万元起，依次级别为2倍递增。'/>
                         <ProFormRadio.Group name='status' label='状态'
                              options={[{label:'正常',value:1},{label:'关闭',value:2,style:{color:'blue'}},
                                    {label:'删除',value:3,style:{color:'red'}}]}
                            />
                           <ProFormDatePicker name='operate_time' label='操作时间'/>
                         <ProFormSelect name='operater_id' label='操作人' width={300}
                                 showSearch
                                 request={async ()=>{
                                        const x=await s_getSelectData({x_id:1,source:'base_person'});
                                        return x.data;}}
                          />
                    </Col>
                </Row>
   
             </ProForm>
        </Modal>
        </ProCard>
        </>
    );
}

export default App;

